package com.knight.hadoop.day10.inver.index;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 实现倒排索引，内容类似于类目录下的txt的文件内容
 * 
 * a.txt的内容： hello tom hello jerry hello tom
 * 
 * b.txt的内容 hello jerry hello jerry tom jerry
 * 
 * c.txt内容 hello jerry hello tom
 * 
 * 最后结果： hello a.txt-3 b.txt-2 c.txt-2 tom a.txt-2 b.txt1 c.txt-1 jerry a.txt-1
 * b.txt-3 c.txt-1
 * 
 * 实现方法： 将单词和文件名作为key，value就是该单词在该文件出现的次数，结果如下： hello-a.txt 3 hello-b.txt 2
 * hello-c.txt 2
 * 
 * 第二步： 将第一步作为输入，使用hello作为key，文件和次数为value，结果如下: hello a.txt 3 b.txt 2 c.txt 2
 * 实现业务需求
 * 
 * @author
 *
 */
public class InverIndexStepOne {

	static class InverIndexStepOneMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

		Text outPutKey = new Text();
		IntWritable outPutValue = new IntWritable(1);

		@Override
		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

			String line = value.toString();

			// 获取文件名
			FileSplit fileSplit = (FileSplit) context.getInputSplit();
			String fileName = fileSplit.getPath().getName();

			String[] values = line.split(" ");
			
			for(String str:values){
				outPutKey.set(str + "-" + fileName);
				context.write(outPutKey, outPutValue);
			}
		}
	}

	static class InverIndexStepOneReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
		
		Text outPutKey = new Text();
		IntWritable outPutValue = new IntWritable(1);
		
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			
			int sum = 0;
			for(IntWritable intWritable: values){
				sum+=intWritable.get();
			}
			
			outPutValue.set(sum);
			
			context.write(key, outPutValue);
			
		}
	}
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(InverIndexStepOne.class);
		
		job.setMapperClass(InverIndexStepOneMapper.class);
		job.setReducerClass(InverIndexStepOneReducer.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
	
		FileInputFormat.setInputPaths(job, new Path("E:/home/inverIndex/input"));
		FileOutputFormat.setOutputPath(job, new Path("E:/home/inverIndex/output"));
		
		boolean res = job.waitForCompletion(true);
		System.exit(res?0:1);
	}

}
